package com.dqp.cslggroup.yunPrint;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;

import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.dqp.cslggroup.EventBus.MessageEvent;
import com.dqp.cslggroup.JWXT.JWXT_main;
import com.dqp.cslggroup.JWXT.login_JWXT;
import com.dqp.cslggroup.R;
import com.dqp.cslggroup.UI.BaseActivity;
import com.dqp.cslggroup.UI.MyApplication;
import com.dqp.cslggroup.Util.ToastUtil;
import com.dqp.cslggroup.Util.verification;
import com.dqp.cslggroup.bean.student;


import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jsoup.Connection;
import org.jsoup.Jsoup;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;


import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static com.dqp.cslggroup.UI.MyApplication.getContext;

public class creatOrder extends BaseActivity {
    EditText name, sno, dormitory, phone;
    Spinner mode, copies;
    TextView filePath, countView, msgView;
    String url = "http://210.28.164.4:9999/printorder/yunprint/";
    String userName, userSno, userDormitory, userPhone, userMode;
    int userCopies;
    String path;
    ImageView add_img;
    Button button;
    String count, msg, price;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.yunprint);
        EventBus.getDefault().register(this);
        initCmp();
        new Thread(this::getSettingInfo).start();
    }

    public void initCmp() {
        InputMethodManager manager = ((InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE));
        name = findViewById(R.id.name);
        sno = findViewById(R.id.sno);
        dormitory = findViewById(R.id.dormitory);
        phone = findViewById(R.id.phone);
        copies = findViewById(R.id.copies);
        mode = findViewById(R.id.mode);
        filePath = findViewById(R.id.path);
        add_img = findViewById(R.id.add_img);
        countView = findViewById(R.id.count);
        msgView = findViewById(R.id.msg);
        button = findViewById(R.id.submitOrder);
        add_img.setOnClickListener(v ->
        {
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("*/*");//无类型限制
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            startActivityForResult(intent, 1);
        });
        button.setOnClickListener(view -> {
            userName = name.getText().toString();
            userSno = sno.getText().toString();
            userPhone = phone.getText().toString();
            userCopies = copies.getSelectedItemPosition() + 1;
            userDormitory = dormitory.getText().toString();
            switch (mode.getSelectedItemPosition()) {
                case 1:
                    userMode = "TWO_SIDED_LONG_EDGE";
                    break;
                case 2:
                    userMode = "TWO_SIDED_SHORT_EDGE";
                    break;
                default:
                    userMode = "ONE_SIDED";
            }
            if (userName == null || userPhone == null || userSno == null || userMode == null || userDormitory == null || userName.length() < 1 || userSno.length() != 9 || userPhone.length() != 11 || path.length() < 3) {
                ToastUtil.showToast("请完整填写相关信息！");
            } else {
                if (manager != null)
                    manager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                if (button.getText().equals("提交订单")) {
                    new Thread(() -> putOrder(path)).start();
                } else {
                }
            }
        });
        initStudentInfo();
    }

    public JSONObject putOrder(String path) {
        JSONObject jsonObject = null;
        File file = new File(path);
        RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", file.getName(), fileBody)
                .build();
        Request request = new Request.Builder()
                .url(url + "creatPrintOrder/name=" + userName + "&sno=" + userSno + "&dormitory=" + userDormitory + "&phone=" + userPhone + "&copies=" + userCopies + "&mode=" + userMode)
                .post(requestBody)
                .build();
        final okhttp3.OkHttpClient.Builder httpBuilder = new OkHttpClient.Builder();
        OkHttpClient okHttpClient = httpBuilder.build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String body = response.body().string();
                JSONObject json = JSON.parseObject(body);
                if (json!=null&&json.containsKey("result")&&"success".equals(json.getString("result")))
                    EventBus.getDefault().post(new MessageEvent("creatOrder", 0, json));
            }

            @Override
            public void onFailure(Call arg0, IOException e) {
                // TODO Auto-generated method stub
                Log.e("IOException", e.toString());
                EventBus.getDefault().post(new MessageEvent("creatOrder", 1, null));
            }

        });
        return jsonObject;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == Activity.RESULT_OK && data != null) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            assert selectedImage != null;
            Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
            assert cursor != null;
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            path = cursor.getString(columnIndex);
            cursor.close();
            if (path != null && path.length() > 0) {
                filePath.setText(path);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        if (event.getEvent().equals("creatOrder")) {
            if (event.getWhat() == 0) {
                JSONObject jsonObject= (JSONObject) event.getObj();

                //ToastUtil.showToast("订单:"+jsonObject.getJSONObject("Details").getString("outtradeno")+"提交成功!\n我们将及时打印并配送！");

                Intent intent = new Intent(this, confirmOrder.class);
                intent.putExtra("json", (Serializable) jsonObject.getJSONObject("Details").toJSONString());
                intent.setClass(this, confirmOrder.class);
                startActivity(intent);



            }
            if (event.getWhat() == 1) {
                ToastUtil.showToast("订单创建失败！");
            }
            if (event.getWhat() == 2) {
                String body = event.getMessage();
                JSONObject json = JSON.parseObject(body);
                if (json != null && json.containsKey("result") && json.getString("result").equals("success"))
                    EventBus.getDefault().post(new MessageEvent("creatOrder", 0, null));
            }
            if (event.getWhat() == 3) {
                countView.setText("订单数："+count);
                msgView.setText("单价："+price + "/面");
            }
        }

    }

    @SuppressLint("HandlerLeak")
    private void initStudentInfo() {
        ArrayList<String> dataList = new ArrayList<>();
        List<student> studentList = MyApplication.getDaoInstant().getStudentDao().loadAll();
        if (studentList.size() > 0) {
            userSno = studentList.get(0).getXh();
            userName = studentList.get(0).getXm();
            name.setText(userName);
            sno.setText(userSno);
        }
    }

    @SuppressLint("HandlerLeak")
    private void getSettingInfo() {
        Connection.Response response = null;
        try {
            response = Jsoup.connect(url + "getOrderSetting")
                    .ignoreContentType(true)
                    .method(Connection.Method.GET)
                    .timeout(5000)
                    .execute();
            System.out.println(response.body());
        } catch (IOException e) {
            e.printStackTrace();
            return ;
        }
        JSONObject jsonObject = JSON.parseObject(response.body());
        if (jsonObject != null && jsonObject.containsKey("result") && "success".equals(jsonObject.getString("result"))) {
            count = jsonObject.getString("orderCount");
            msg = jsonObject.getString("msg");
            price = jsonObject.getString("price");
            EventBus.getDefault().post(new MessageEvent("creatOrder", 3, null));
        }
    }




}
